package ua.kharkov.khpi.tarasenko.bach.web.command.admin;

import java.sql.Connection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDAO;
import ua.kharkov.khpi.tarasenko.bach.dao.core.user.UserDTO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to show list of registered users.
 * 
 * @author oleksandr
 * 
 */
public class ShowUsersListCommand extends Command {
	private static final Logger log = Logger
			.getLogger(ShowUsersListCommand.class);

	private static final String ATTRIBUTE_USERS_LIST = "usersList";

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String forward = Constant.PAGE_USERS_LIST;
		Connection conn = null;

		try {
			conn = ConnectionManager.getConnection();
			UserDAO userDAO = DAOFactory.getDAOFactory(
					DAOFactory.DAO_TYPE.MYSQL).getUserDAO(conn);

			List<UserDTO> users = userDAO.findAllUsers();
			request.setAttribute(ATTRIBUTE_USERS_LIST, users);
			if (log.isTraceEnabled()) {
				log.trace("Set request attribute " + ATTRIBUTE_USERS_LIST
						+ ":\n" + users);
			}
		} catch (EShopException e) {
			DBUtils.close(conn);
			throw e;
		} finally {
			if (conn != null) {
				DBUtils.close(conn);
			}
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}

		return forward;
	}

}
